import { useEffect, useRef, useState } from 'react'
import { useMemoizedFn } from 'ahooks'
import copy from 'copy-to-clipboard'
import { Button, Card, Input, message, Popover } from 'antd'
import { CopyOutlined, EditOutlined } from '@ant-design/icons'

import { VCenterEmpty } from '@/components/VCenterEmpty'
import { isValidURL } from '@/utils/utils'
import { LogisticsIcon } from '@oBiz/components/LogisticsIcon'
import { eventBus } from '@oBiz/TrackOrder/Detail/utils'
import { apiGetLogisticsInfo, apiUpdateCardInfo } from './apis'
import { ILogisticsInfo } from './interface'
import styles from './styles.module.less'
interface IProps {
  waybillNo: string
}

export const Logistics = (props: IProps) => {
  const { waybillNo } = props
  const [logisticsInfo, setLogisticsInfo] = useState<ILogisticsInfo>({} as ILogisticsInfo) //物流信息
  const [carrierFlag, setCarrierFlag] = useState<boolean>(false)
  const [shipNameFlag, setShipNameFlag] = useState<boolean>(false)
  const [containerNumberFlag, setContainerNumberFlag] = useState<boolean>(false)
  const [voyageFlag, setVoyageFlag] = useState<boolean>(false)
  const infoRef = useRef<ILogisticsInfo>({} as ILogisticsInfo)
  const [loading, setLoading] = useState<boolean>(false)

  // 请求接口
  const initData = useMemoizedFn(async () => {
    try {
      setLoading(true)
      const data = await apiGetLogisticsInfo(waybillNo)
      setLogisticsInfo(data)
      infoRef.current = data as ILogisticsInfo
    } finally {
      setLoading(false)
    }
  })
  // 复制
  const copyHandler = useMemoizedFn((text: string | undefined) => {
    if (!text) return
    copy(`${text}`)
    message.success('复制成功', 1)
  })

  //内容调整
  const onChangeHandler = useMemoizedFn((value, key) => {
    infoRef.current = { ...infoRef.current, [key]: value }
  })

  // 保存
  const onSaveHandler = useMemoizedFn(async key => {
    if (key === 'carrier') {
      if (!infoRef.current.carrier || infoRef.current.carrier === logisticsInfo?.carrier) return setCarrierFlag(false)
      await apiUpdateCardInfo({ waybillNo, carrier: infoRef.current.carrier })
      setCarrierFlag(false)
      setLogisticsInfo(infoRef.current)
    }
    if (key === 'shipName') {
      if (!infoRef.current.shipName || infoRef.current.shipName === logisticsInfo?.shipName) {
        return setShipNameFlag(false)
      }
      await apiUpdateCardInfo({ waybillNo, shipName: infoRef.current.shipName })
      setShipNameFlag(false)
      setLogisticsInfo(infoRef.current)
    }
    if (key === 'containerNumberUrl') {
      if (!isValidURL(infoRef.current.containerNumberUrl) && infoRef.current.containerNumberUrl) {
        return message.warning('链接格式有误')
      }
      if (
        !infoRef.current.containerNumberUrl ||
        infoRef.current.containerNumberUrl === logisticsInfo?.containerNumberUrl
      ) {
        return setContainerNumberFlag(false)
      }
      await apiUpdateCardInfo({ waybillNo, containerNumberUrl: infoRef.current.containerNumberUrl })
      setContainerNumberFlag(false)
      setLogisticsInfo(infoRef.current)
    }
    if (key === 'voyage') {
      if (!isValidURL(infoRef.current.voyageUrl) && infoRef.current.voyageUrl) {
        return message.warning('链接格式有误')
      }
      if (
        infoRef.current.voyageUrl === logisticsInfo?.voyageUrl &&
        infoRef.current.voyageNumber === logisticsInfo?.voyageNumber
      ) {
        return setVoyageFlag(false)
      }
      await apiUpdateCardInfo({
        waybillNo,
        voyageUrl: infoRef.current.voyageUrl,
        voyageNumber: infoRef.current.voyageNumber,
      })
      setVoyageFlag(false)
      setLogisticsInfo(infoRef.current)
    }
  })

  // 转单号变更
  useEffect(() => eventBus.on('transferOrderNumChanged', () => initData()), [initData])

  useEffect(() => {
    initData()
  }, [initData, waybillNo])

  return (
    <Card className={styles.card} title="物流信息" loading={loading}>
      {!logisticsInfo ? (
        VCenterEmpty.render()
      ) : (
        <div className={styles.box}>
          <div className={styles.logistics}>
            <LogisticsIcon className={styles.icon} type={logisticsInfo?.iconType} />
            <div className={styles.logistics_text}>
              <div>{logisticsInfo?.logisticsName || '--'}</div>
              <span>{logisticsInfo?.logisticsCode}</span>
            </div>
          </div>
          <div className={styles.contain}>
            <div className={styles.item}>
              <span className={styles.label}>尾程派送</span>
              <span>{logisticsInfo?.deliveryTail || '--'}</span>
            </div>
            <div className={styles.item}>
              <span className={styles.label}>转单号</span>
              <Popover
                overlayInnerStyle={{ width: '200px' }}
                content={
                  <div className={styles.orderTips}>
                    <span className={styles.orderContent}>{logisticsInfo?.trackingNumberList?.join(',')}</span>
                    <Button
                      type="link"
                      onClick={() => {
                        if (logisticsInfo && logisticsInfo?.trackingNumberList?.length > 0) {
                          copyHandler(logisticsInfo?.trackingNumberList.join(','))
                        }
                      }}
                    >
                      复制
                    </Button>
                  </div>
                }
              >
                <span className={styles.orderNum}>
                  {logisticsInfo && logisticsInfo?.trackingNumberList?.length > 0
                    ? `${logisticsInfo?.trackingNumberList[0]}(${logisticsInfo?.trackingNumberList.length})`
                    : '--'}
                </span>
              </Popover>
            </div>
            <div className={styles.item}>
              <span className={styles.label}>尾程服务商</span>
              <span>{logisticsInfo?.merchantServersTail || '--'}</span>
            </div>
            <div className={styles.item}>
              <span className={styles.label}>Carrier</span>
              <span>{logisticsInfo?.carrier || '--'}</span>
              <CopyOutlined
                className={styles.copyIcon}
                onClick={() => {
                  copyHandler(logisticsInfo?.carrier)
                }}
              />
              <Popover
                overlayInnerStyle={{ width: '400px' }}
                open={carrierFlag}
                trigger="click"
                destroyTooltipOnHide={true}
                content={
                  <div>
                    <div className={styles.flex}>
                      <span>Carrier</span>
                      <Input
                        defaultValue={infoRef.current?.carrier}
                        onChange={e => {
                          onChangeHandler(e.target.value, 'carrier')
                        }}
                        placeholder="请输入内容"
                      />
                    </div>
                    <div className={styles.footer}>
                      <Button
                        onClick={() => {
                          setCarrierFlag(false)
                          infoRef.current = logisticsInfo
                        }}
                      >
                        取消
                      </Button>
                      <Button
                        type="primary"
                        onClick={() => {
                          onSaveHandler('carrier')
                        }}
                      >
                        保存
                      </Button>
                    </div>
                  </div>
                }
              >
                <EditOutlined
                  className={styles.editIcon}
                  onClick={() => {
                    setCarrierFlag(true)
                  }}
                />
              </Popover>
            </div>
            <div className={styles.item}>
              <span className={styles.label}>船名</span>
              <span>{logisticsInfo?.shipName || '--'}</span>
              <CopyOutlined
                className={styles.copyIcon}
                onClick={() => {
                  copyHandler(logisticsInfo?.shipName)
                }}
              />
              <Popover
                overlayInnerStyle={{ width: '400px' }}
                open={shipNameFlag}
                trigger="click"
                destroyTooltipOnHide={true}
                content={
                  <div>
                    <div className={styles.flex}>
                      <span>船名</span>
                      <Input
                        defaultValue={logisticsInfo?.shipName}
                        onChange={e => {
                          onChangeHandler(e.target.value, 'shipName')
                        }}
                        placeholder="请输入内容"
                      />
                    </div>
                    <div className={styles.footer}>
                      <Button
                        onClick={() => {
                          setShipNameFlag(false)
                          infoRef.current = logisticsInfo
                        }}
                      >
                        取消
                      </Button>
                      <Button
                        type="primary"
                        onClick={() => {
                          onSaveHandler('shipName')
                        }}
                      >
                        保存
                      </Button>
                    </div>
                  </div>
                }
              >
                <EditOutlined
                  className={styles.editIcon}
                  onClick={() => {
                    setShipNameFlag(true)
                  }}
                />
              </Popover>
            </div>
            <div className={styles.item}>
              <span className={styles.label}>航次</span>
              <span
                onClick={() => {
                  if (logisticsInfo?.voyageUrl) window.open(logisticsInfo?.voyageUrl, '_blank')
                }}
                className={logisticsInfo?.voyageUrl ? styles.blue : ''}
              >
                {logisticsInfo?.voyageNumber || '--'}
              </span>
              <CopyOutlined
                className={styles.copyIcon}
                onClick={() => {
                  copyHandler(logisticsInfo?.voyageNumber)
                }}
              />
              <Popover
                overlayInnerStyle={{ width: '400px' }}
                open={voyageFlag}
                trigger="click"
                destroyTooltipOnHide={true}
                content={
                  <div>
                    <div className={styles.flex}>
                      <span>航次</span>
                      <Input
                        defaultValue={logisticsInfo?.voyageNumber}
                        onChange={e => {
                          onChangeHandler(e.target.value, 'voyageNumber')
                        }}
                        placeholder="请输入内容"
                      />
                    </div>
                    <div className={styles.flex}>
                      <span>链接</span>
                      <Input
                        defaultValue={logisticsInfo?.voyageUrl}
                        onChange={e => {
                          onChangeHandler(e.target.value, 'voyageUrl')
                        }}
                        placeholder="请输入内容"
                      />
                    </div>
                    <div className={styles.footer}>
                      <Button
                        onClick={() => {
                          setVoyageFlag(false)
                          infoRef.current = logisticsInfo
                        }}
                      >
                        取消
                      </Button>
                      <Button
                        type="primary"
                        onClick={() => {
                          onSaveHandler('voyage')
                        }}
                      >
                        保存
                      </Button>
                    </div>
                  </div>
                }
              >
                <EditOutlined
                  className={styles.editIcon}
                  onClick={() => {
                    setVoyageFlag(true)
                  }}
                />
              </Popover>
            </div>
            <div className={styles.item}>
              <span className={styles.label}>柜号</span>
              <span
                onClick={() => {
                  if (logisticsInfo?.containerNumberUrl) window.open(logisticsInfo?.containerNumberUrl, '_blank')
                }}
                className={logisticsInfo?.containerNumberUrl ? styles.blue : ''}
              >
                {logisticsInfo?.containerNumber || '--'}
              </span>
              <CopyOutlined
                className={styles.copyIcon}
                onClick={() => {
                  copyHandler(logisticsInfo?.containerNumber)
                }}
              />
              <Popover
                overlayInnerStyle={{ width: '400px' }}
                open={containerNumberFlag}
                trigger="click"
                destroyTooltipOnHide={true}
                content={
                  <div>
                    <div className={styles.flex}>
                      <span>链接</span>
                      <Input
                        defaultValue={logisticsInfo?.containerNumberUrl}
                        onChange={e => {
                          onChangeHandler(e.target.value, 'containerNumberUrl')
                        }}
                        placeholder="请输入链接"
                      />
                    </div>
                    <div className={styles.footer}>
                      <Button
                        onClick={() => {
                          setContainerNumberFlag(false)
                          infoRef.current = logisticsInfo
                        }}
                      >
                        取消
                      </Button>
                      <Button
                        type="primary"
                        onClick={() => {
                          onSaveHandler('containerNumberUrl')
                        }}
                      >
                        保存
                      </Button>
                    </div>
                  </div>
                }
              >
                <EditOutlined
                  className={styles.editIcon}
                  onClick={() => {
                    setContainerNumberFlag(true)
                  }}
                />
              </Popover>
            </div>
          </div>
        </div>
      )}
    </Card>
  )
}
